package com.kaka.bus.engine.home.info.borrowlist.deteil;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.adapter.BorrowDeteilAdapter;
import com.kaka.bus.api.RetrofitUtils;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.BorrowDeteil;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.UserConstant;
import com.kaka.bus.engine.borrow.phone.ForGetServiceActivity;
import com.kaka.bus.engine.repay.RepayActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.util.FileIOUtils;
import com.kaka.bus.util.StatusBarUtil;
import com.kaka.bus.util.U;
import com.kaka.bus.util.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;

import butterknife.BindView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by OnionMac on 2018/1/3.
 */

public class BorrowDeteilActivity extends BaseActivity<BorrowDeteilPresenter> implements BorrowDeteilContract.View {


    @BindView(R.id.repayplan_contract)
    TextView mRepayplanContract;
    @BindView(R.id.repayplan_title)
    TextView mRepayplanTitle;
    @BindView(R.id.repayplan_money_surplus)
    TextView mRepayplanMoneySurplus;
    @BindView(R.id.repayplan_money_total)
    TextView mRepayplanMoneyTotal;
    @BindView(R.id.repayplan_coor_ll)
    LinearLayout mRepayplanCoorLl;
    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.repayplan_overdue)
    TextView mRepayplanOverdue;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.collapsing_toolbar_layout)
    CollapsingToolbarLayout mCollapsingToolbarLayout;
    @BindView(R.id.app_bar_layout)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.repayplan_bill)
    TextView mRepayplanBill;
    @BindView(R.id.repayplan_tips)
    TextView mRepayplanTips;
    @BindView(R.id.repayplan_recy)
    RecyclerView mRepayplanRecy;
    @BindView(R.id.repayplan_swipe)
    SwipeRefreshLayout mRepayplanSwipe;
    @BindView(R.id.repayplan_coor)
    CoordinatorLayout mRepayplanCoor;
    @BindView(R.id.repayplan_ll)
    LinearLayout mRepayplanLl;

    public static final String BORROWID = "borrowId";

    @BindView(R.id.submit_action)
    TextView msubmit;
    @BindView(R.id.submit_go)
    TextView msubmitGo;
    @BindView(R.id.borrow_singlepay)
    TextView mBorrowSinglePay;
    @BindView(R.id.bottom_btn)
    LinearLayout mBottomBtn;
    private boolean mIsDownPdf;

    private String mBorrowId, mStatus;
    private RxPermissions mRxPermissions;
    private String mContractUrl;
    BorrowDeteil mBorrowDeteil = null;
    private ArrayList<BorrowDeteil.PlanListBean> mData = new ArrayList<>();
    private BorrowDeteilAdapter mBorrowDeteilAdapter;

    private final int mCanEarlyPay = 1;

    /**
     * 最后一期
     */
    private final int mIsLast = 1;

    @Override
    protected void initView() {
        super.initView();
        mRxPermissions = new RxPermissions(this);
        mRepayplanSwipe.setProgressViewEndTarget(false, 300);
        mRepayplanSwipe.setColorSchemeColors(getResources().getColor(R.color.toolbar_color));

        mToolbarBack.setOnClickListener(v -> finish());
        mToolbarName.setText("回收详情");
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        TypedValue tv = new TypedValue();
        if (this.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, this.getResources().getDisplayMetrics());
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mRepayplanCoorLl.getLayoutParams();
            int barHeight = U.getBarHeight(this.getApplication());
            params.topMargin = actionBarHeight + barHeight + 10;
            mRepayplanCoorLl.setLayoutParams(params);
        }

        mRepayplanContract.setVisibility(View.VISIBLE);
        mRepayplanTips.setVisibility(View.VISIBLE);

        mRepayplanRecy.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mBorrowDeteilAdapter = new BorrowDeteilAdapter(R.layout.item_borrowdeteil, mData);
        mRepayplanRecy.setAdapter(mBorrowDeteilAdapter);
        mBorrowDeteilAdapter.bindToRecyclerView(mRepayplanRecy);
        mBorrowDeteilAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                View goneView = adapter.getViewByPosition(position, R.id.extendsview);
                View second_view = adapter.getViewByPosition(position, R.id.second_view);
                ImageView img = (ImageView) adapter.getViewByPosition(position, R.id.tip_img);
                if (goneView.getVisibility() == View.VISIBLE) {
                    goneView.setVisibility(View.GONE);
                    img.setImageResource(R.drawable.huishouxiangqing_icon_open);
                } else {
                    img.setImageResource(R.drawable.huishouxiangqing_icon_close);
                    goneView.setVisibility(View.VISIBLE);
                    BorrowDeteil.PlanListBean pos = (BorrowDeteil.PlanListBean) adapter.getData().get(position);
                    if (mIsLast == pos.getIsLast()){
                        second_view.setVisibility(View.VISIBLE);
                        TextView phonepay = second_view.findViewById(R.id.item_borrowdeteil_money4);
                        TextView money = second_view.findViewById(R.id.item_borrowdeteil_money5);
                        phonepay.setText(AppCenter.mDf.format(Double.parseDouble(mBorrowDeteil.getRansomAmount())));

                        double amout = Double.parseDouble(mBorrowDeteil.getDepositAmount());
                        if(amout == 0){
                            money.setText(U.connectString(AppCenter.mDf.format(amout)));
                        }else{
                            money.setText(U.connectString("-",AppCenter.mDf.format(amout)));
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        mBorrowId = intent.getStringExtra(BORROWID);
        //  mStatus=intent.getStringExtra(STATUS);
    }

    @Override
    protected void initDataOnStart() {
        super.initDataOnStart();
        mPresenter.getBorrowDeteil(getUserId(), getToken(), mBorrowId);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mRepayplanSwipe.setOnRefreshListener(() -> mPresenter.getBorrowDeteil(getUserId(), getToken(), mBorrowId));
        msubmit.setOnClickListener(view -> {
                //付款
                toRepay(RepayActivity.TYPE_TERM_NOW);
        });
        msubmitGo.setOnClickListener(view -> {
            //提前结清
                toRepay(RepayActivity.TYPE_ALL);
        });
        mBorrowSinglePay.setOnClickListener(view -> {
                toRepay(RepayActivity.TYPE_TERM_NOW);
        });
        /**
         * 回收合同
         */
//        mRepayplanContract.setOnClickListener(view -> {
//            mRxPermissions
//                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE)
//                    .subscribe(bool -> {
//                        if(bool){
//                            /**
//                             * 判断SD卡是否挂载
//                             */
//                            if(SDCardUtils.isSDCardEnable()){
//                                if(TextUtils.isEmpty(mContractUrl)){
//                                    showMessage("暂无合同");
//                                    return;
//                                }
//                                downContract(mContractUrl);
//                            }else{
//                                showMessage("您没有挂载内置SD卡,无法下载合同");
//                            }
//                        }else{
//                            ToastUtil.showLong(this,"您已经拒绝了权限,请在设置-应用管理中打开读取读写权限");
//                        }
//                    });
//        });
        mRepayplanContract.setOnClickListener(v -> {


            if(TextUtils.isEmpty(mContractUrl)){
                showMessage("协议正在处理中,请稍后!");
                return;
            }

            Intent intent = new Intent(this, ForGetServiceActivity.class);
            intent.putExtra("yunying", "合同");
            intent.putExtra("url", mContractUrl);
            startActivity(intent);
        });
    }

    public void toRepay(int type){
        Intent intent = new Intent(this, RepayActivity.class);
        intent.putExtra(UserConstant.BORR_ID, mBorrowId);
        intent.putExtra(RepayActivity.TYPE, type);
        startActivity(intent);
    }

    /**
     * BS002取消合同
     */
    private void dialogShow() {
        U.getSlectDialog(BorrowDeteilActivity.this, "提示", "您是否确认取消此回收吗？", "确定", "取消", new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {
                 mPresenter.cancelRequest(getUserId(),getToken(),mBorrowId);
            }

            @Override
            public void onRight() {

            }
        }).show();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_repayplan;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }
    public void closeRefresh() {
        if (mRepayplanSwipe == null) {
            return;
        }

        if (mRepayplanSwipe.isRefreshing()) {
            mRepayplanSwipe.setRefreshing(false);
        }
    }

    @Override
    public void getDeteilResult(HttpWrapper<BorrowDeteil> data) {
        closeRefresh();
        BorrowDeteil o = data.getData();
        if(Constant.SUCCESS_CODE.equals(data.code)){
            mBorrowDeteil = o;
            mContractUrl = mBorrowDeteil.getContractUrl();
            mStatus = o.getBorrStatus();
            mRepayplanMoneySurplus.setText(o.getSurplusAmount());
            mRepayplanMoneyTotal.setText(U.connectString("租赁期限 ",o.getTermNum(),"期"));
            mData.clear();
            mData.addAll(o.getPlanList());
            mBorrowDeteilAdapter.notifyDataSetChanged();

            if (mStatus.equals("BS004") || mStatus.equals("BS005")) {
                mBottomBtn.setVisibility(View.VISIBLE);
                if(mBorrowDeteil.getEarlySettlement() == mCanEarlyPay){
                    mBorrowSinglePay.setVisibility(View.GONE);
                    msubmit.setVisibility(View.VISIBLE);
                    msubmitGo.setVisibility(View.VISIBLE);
                }else{
                    mBorrowSinglePay.setVisibility(View.VISIBLE);
                    msubmit.setVisibility(View.GONE);
                    msubmitGo.setVisibility(View.GONE);
                }
                msubmit.setText("付款");
                msubmitGo.setText("提前结清");
            } else {
                mBottomBtn.setVisibility(View.GONE);
            }

            if(o.getOverdueDays() > 7){
                mRepayplanOverdue.setText(U.connectString("※您已逾期超过","七","天,我们会强制回购您的手机"));
                mRepayplanOverdue.setVisibility(View.GONE);
            }
        }
        
    }

    /**
     * 下载PDF后 然后提示用户用第三方打开
     * @param data
     */
    private void downContract(String data) {
        String fileName = U.connectString("手机回收合同", mBorrowDeteil.getBorrId(), ".pdf");
        String location = Environment.getExternalStorageDirectory().getPath() + File.separator+Constant.CONTRACT_FILE;
        File file = new File(location);
        if(!file.exists()){
            Logger.i("合同文件夹已经存在");
            file.mkdir();
        }

        File elocation = new File(file,fileName);
        Logger.i("保存的地址"+location);
        /**
         * 如果当前下载过 则不需要下载
         */
        if(mIsDownPdf){
            Logger.i("当前下载过合同 无需下载合同");
            showContractTips(Constant.CONTRACT_FILE,elocation);
            return;
        }

        showDialog("正在下载合同");
        Call<ResponseBody> call = RetrofitUtils.getInstance().build().downPDF(data);
        Logger.i("下载合同id"+data);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                dissDialog();
                if(response.isSuccessful()){
                    InputStream inputStream = response.body().byteStream();
                    boolean flag = FileIOUtils.writeFileFromIS(elocation, inputStream);
                    Logger.i(location);
                    if(flag){
                        mIsDownPdf = true;
                        showContractTips(Constant.CONTRACT_FILE,elocation);
                    }else{
                        showMessage("下载失败"+location);
                    }
                }else{
                    showMessage("下载失败,请检查网络");
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                dissDialog();
            }
        });
    }

    private void showContractTips(String location,File elocation) {
        U.getSlectDialog(this, "提醒", "手机回收合同保存在" + location, "取消", "立即查看", new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {

            }

            @Override
            public void onRight() {
                Uri path = Uri.fromFile(elocation);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                try {
                    startActivity(intent);
                }
                catch (ActivityNotFoundException e) {
                    // 没有任何PDF
                    e.printStackTrace();
                    showMessage("请您安装PDF查看器,查看您当前的合同");
                }
            }
        }).show();
    }

    @Override
    public void refresh() {
        finish();
    }

}
